import { parse } from 'qs'
import modelExtend from 'dva-model-extend'
import queryString from 'query-string'
import { message } from 'antd'
import { query } from '../services/dashboard'
import { pageModel } from './common'
import * as basicData from '../services/basicData.js'
import { list } from '../services/exchangerate'

export default modelExtend(pageModel, {
  namespace: 'dashboard',
  state: {
    sales: [],
    numbers: [],
    currenciesTypeData: [],
    currenciesCodeMapName: [],
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen(({ pathname,search }) => {
        if (pathname === '/dashboard' || pathname === '/') {
          const payload = queryString.parse(search) || { page: 1 }
          dispatch({ type: 'query' })
          dispatch({ type: 'list',payload})
        }
      })
    },
  },
  effects: {
    * query ({
      payload,
    }, { call, put }) {
      const data = yield call(query, parse(payload))
      yield put({
        type: 'updateState',
        payload: data,
      })
    },
    * list ({ payload = {} }, { call, put }) {
      const data = yield call(list, payload)
      const listData = data.data
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: listData.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: listData.total,
            },
          },
        })
      }
    },
  },
})
